package lion.project.blackboard_for_education;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 描画クラスの定義
 * 
 * @author yasi_life
 * 
 */
public class DrawView extends View {

	private ArrayList<Point> draw_list = new ArrayList<Point>();
	// おはじきの位置情報
	private ArrayList<Point> mOhaziki_draw_list = new ArrayList<Point>();

	private int color;

	// 描画オブジェクト
	private static final int LINE_OBJECT = 0;
	private static final int OHAZIKI_OBJECT = 1;

	// おはじき画像
	public Bitmap mOhazikiImg;

	// 描くオブジェクト
	private int mObjectToDraw = 0;

	public void setObjectToDraw(int objectNo) {
		mObjectToDraw = objectNo;
	}

	public DrawView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setFocusable(true);
		this.color = Color.WHITE;
		setBackgroundResource(R.drawable.blackboard);

		// おはじき画像
		mOhazikiImg = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ohaziki);
	}

	/**
	 * 描画を行うイベント
	 */
	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		Paint paint = new Paint();

		paint.setColor(Color.BLUE);
		paint.setColor(color);
		paint.setStyle(Paint.Style.FILL);
		paint.setStrokeWidth(4);
		// 記録した座標を順に繋げて描画する
		Point q = new Point(-1, -1);
		for (int i = 0; i < draw_list.size(); i++) { // 記憶された座標を次々と描画
			Point p = draw_list.get(i);
			if (p.x >= 0) {
				if (q.x < 0) {
					q = p;
				}
				canvas.drawLine(q.x, q.y, p.x, p.y, paint);
			}
			q = p;
		}

		// おはじきを描画
		for (Point ohazikiPoint : mOhaziki_draw_list) {
			canvas.drawBitmap(mOhazikiImg, ohazikiPoint.x, ohazikiPoint.y, null);
		}
	}

	/**
	 * タッチイベントで座標をArrayListに追加
	 */
	public boolean onTouchEvent(MotionEvent event) {
		int x = (int) event.getX();
		int y = (int) event.getY();

		switch (mObjectToDraw) {
		case LINE_OBJECT:
			draw_list.add(new Point(x, y)); //ArrayListに座標を追加
			if (event.getAction() == MotionEvent.ACTION_UP) {
				draw_list.add(new Point(-1, -1)); // 
			}
			break;
		case OHAZIKI_OBJECT:
			mOhaziki_draw_list.add(new Point(x, y));
			break;
		}

		invalidate(); //再描画
		return true;
	}

	public void setColor(int color) {
		this.color = color;
	}

	public int getColor() {
		return color;
	}
}
